//
//  ThreadSafeController.m
//  TEXT
//
//  Created by liubo on 2023/5/5.
//  Copyright © 2023 刘博. All rights reserved.
//

#import "ThreadSafeController.h"

@interface ThreadSafeController ()

@property (nonatomic, strong) NSArray *dataArray;

@property (nonatomic, strong) NSLock *lock;

@property (atomic, assign) NSInteger sliece;

@end

@implementation ThreadSafeController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.lock = [[NSLock alloc] init];
    //[self testThreadSafe];
    [self testThreadSafe2];
    // Do any additional setup after loading the view.
}

- (void)testThreadSafe
{
    self.dataArray = @[@"1", @"2", @"3", @"4", @"5"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        for (int i = 0 ; i < 100; i ++) {
            [self.lock lock];
            self.dataArray = @[@"1", @"2"];
            [self.lock unlock];
        }
        NSLog(@"%@",self.dataArray);
    });
    
    for (int i = 0; i < 10; i ++) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self.lock lock];
            NSLog(@"%@", self.dataArray);
            [self.lock unlock];
        });
    }
}

- (void)testThreadSafe2
{
    dispatch_queue_t queue = dispatch_queue_create("kkk", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        [self.lock lock];
        for (int i = 0; i < 10000; i ++) {
            self.sliece = self.sliece + 1;
        }
        [self.lock unlock];
    });
    dispatch_async(queue, ^{
        [self.lock lock];

        for (int i = 0; i < 10000; i ++) {
            self.sliece = self.sliece + 1;
        }
        [self.lock unlock];
    });
    
    dispatch_after(5, dispatch_get_main_queue(), ^{
        NSLog(@"哈哈值得大小%ld", self.sliece);
    });
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
